import * as d3 from "d3";

export function Zoom(ctx) {

  let context = ctx;

  let _zoom = {};

  /**---------------------------------------------------------------------------
   * 初始化Zoom
   */
  this.initZoom = function(){
    _zoom = d3
      .zoom()
      .scaleExtent([0.1, 4])
      .on("zoom", zoomed);

    context.svg.call(_zoom);
    context.svg.on("dblclick.zoom", null); //禁止双击缩放
  }

  /**---------------------------------------------------------------------------
   * 退回最开始缩放位置
   */
  this.zoomToStart = function() {
    _zoom.on("end.zoomToNode",function() {
      _zoom.scaleTo(context.svg.transition().duration(100),1);
      _zoom.on("end.zoomToNode",null)
    })
    _zoom.translateTo(context.svg.transition().duration(250),100,100);
  }

  /**---------------------------------------------------------------------------
   * 缩进
   */
  this.zoomIn = function() {
    zoomClick(1);
  }

  /**---------------------------------------------------------------------------
   * 缩出
   */
  this.zoomOut = function() {
    zoomClick(-1);
  }

  /**---------------------------------------------------------------------------
   * 缩进到特定节点
   * @param node
   */
  this.zoomToNode = function(node){
    this.zoomToPosition(node.x,node.y);
  }

  /**---------------------------------------------------------------------------
   * 缩进到特定连接
   * @param sNode
   * @param tNode
   */
  this.zoomToLink = function(sNode,tNode) {
    this.zoomToPosition((sNode.x + tNode.x)/2,(sNode.y + tNode.y)/2)
  }


  /**---------------------------------------------------------------------------
   * 向特定方向缩放
   * @param direction
   * @returns {boolean}
   */
  function zoomClick(direction) {
    let factor = 0.2;
    let targetZoom = 1;
    let extent = _zoom.scaleExtent();
    targetZoom = 1 + factor * direction;
    if (targetZoom < extent[0] || targetZoom > extent[1]) {
      return false;
    }
    _zoom.scaleBy(context.svg, targetZoom); // 执行该方法后 会触发zoom事件
  }

  /**---------------------------------------------------------------------------
   * zoom回调方法
   */
  function zoomed() {
    d3.selectAll(".node").attr("transform", d3.event.transform);
    d3.selectAll(".nodetext text").attr("transform", d3.event.transform);
    d3.selectAll(".line").attr("transform", d3.event.transform);
    d3.selectAll(".linetext text").attr("transform", d3.event.transform);
    d3.selectAll(".nodebutton").attr("transform", d3.event.transform);
    //_this.svg.selectAll("g").attr("transform", d3.event.transform);
  }

  /**---------------------------------------------------------------------------
   * 定位到特定位置
   * @param x
   * @param y
   * @param scale
   */
  this.zoomToPosition = function(x, y, scale = 2) {
    _zoom.on("end.zoomToNode",function() {
      _zoom.scaleTo(context.svg.transition().duration(100), scale);
      _zoom.on("end.zoomToNode",null)
    })
    _zoom.translateTo(context.svg.transition().duration(250),x,y);
  }

}
